package cn.huugh.number.service;

import cn.huugh.number.NumberApplication;
import com.google.gson.Gson;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.Buffer;
import java.util.Date;
import java.util.List;

public class NumberService {
    int i=0;
    public int[][] buildImg(List<MyPoint> data,MyPoint pMax){
        int[][] img = new int[512][784];
        for (int i = 0; i < 512; i++) {
            for (int j = 0; j < 784; j++) {
                img[i][j] = 1;  // 初始化图片数组
            }
        }
        // 填充图片、图片放缩
        for(MyPoint mp : data) img[(mp.y*512/pMax.y)-1][(mp.x*784/pMax.x)-1]=0;
        for (int i = 0; i < 512; i++) {
            for (int j = 0; j < 784; j++) {
                System.out.print(img[i][j]);
            }
            System.out.println();
        }
        return img;
    }
    public synchronized void sendImg2Pytorch(int[][] img){
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 512; i++) {
            for (int j = 0; j < 784; j++) {
                sb.append(img[i][j]);  // 序列化
            }
        }
        //System.out.println(sb.toString());
        NumberApplication.modelList.get(0).sendMessage(sb.toString().getBytes());
        NumberApplication.modelList.get(0).sendMessage("OK");
    }

    @Deprecated
    private String createFileWithImg(int[][] img){
        String fileName = new Date().getTime()+i+"";
        File file = new File(fileName);
        Gson gson = new Gson();
        FileOutputStream fos = null;
        try {
            file.createNewFile();
            fos = new FileOutputStream(file);
            fos.write(gson.toJson(img).getBytes());
            fos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        i++;
        System.out.println(img[0].length+"高"+img.length);
        System.out.println(fileName);

        return fileName;
    }
}
